# Read in .KML used to create precinct boundaries
googlePrecincts = 'data/PrecinctBoundaries/Precincts.kml'
lyr <- ogrListLayers(googlePrecincts)
plt <- readOGR(googlePrecincts, layer = lyr) %>% 
    fortify(.)
## OGR data source with driver: KML 
## Source: "data/PrecinctBoundaries/Precincts.kml", layer: "Orange County NC Precincts"
## with 44 features
## It has 2 fields
## Warning in readOGR(googlePrecincts, layer = lyr): Z-dimension discarded
## Regions defined for each Polygons
general <- read_csv("temp/General.csv")
## Parsed with column specification:
## cols(
##   .default = col_character(),
##   age = col_integer(),
##   electionYear = col_integer()
## )
## See spec(...) for full column specifications.
municipal <- read_csv("temp/Municipal.csv")
## Parsed with column specification:
## cols(
##   .default = col_character(),
##   age = col_integer(),
##   electionYear = col_integer()
## )
## See spec(...) for full column specifications.
combined <- rbind(general, municipal)
# Read in Geocoded Chapel HIll, NC coordinates 

chCoordinates <- read_csv("data/chCoordinates") %>%
    select(latitude, longitude)
## Warning: Missing column names filled in: 'X1' [1]
## Parsed with column specification:
## cols(
##   X1 = col_integer(),
##   latitude = col_double(),
##   longitude = col_double()
## )
chCombined <- combined %>%
    filter(municipalityName == 'CHAPEL HILL') %>%
    as.tibble()

chCombined$fullName %>% 
    unique() %>%
    length()
## [1] 31647
# Randomly sample 2000 addresses to test clustering with Leaflet
latlng <- chCoordinates %>% 
    slice(runif(2000,1,34876))

leafletCoords <- latlng[, c(2,1)]
colnames(leafletCoords) <- c("latitude", "longitude")

# Create leaflet map centered on Chapel Hill, add clusters 
map <- leafletCoords %>% 
    leaflet() %>%
    addTiles() %>%
    setView(-79.0534, 35.915, zoom = 13) %>%
    addMarkers(clusterOptions = markerClusterOptions())
## Warning in validateCoords(lng, lat, funcName): Data contains 14 rows with
## either missing or invalid lat/lon values and will be ignored
map
# Exploring the plotting of walking routes. Eventaully will be used to plot the route from a person's home to the nearest polling place or site for public transport.

# Route from UNC CS Department to popular music venue 

from <- '201 S Columbia St, Chapel Hill, NC 27599 '
to <- 'Cat\'s Cradle'
route <- route(from, to, structure = 'route', mode = 'walking')
## Information from URL : http://maps.googleapis.com/maps/api/directions/json?origin=201+S+Columbia+St,+Chapel+Hill,+NC+27599+&destination=Cat's+Cradle&mode=walking&units=metric&alternatives=false&sensor=false
qmap('West Franklin Street, Chapel Hill, NC', zoom = 15, maptype = 'satellite') +
    geom_path(
        aes(x = lon, y = lat),  colour = 'red', size = 1.5,
        data = route, lineend = 'round')
## Map from URL : http://maps.googleapis.com/maps/api/staticmap?center=West+Franklin+Street,+Chapel+Hill,+NC&zoom=15&size=640x640&scale=2&maptype=satellite&language=en-EN&sensor=false
## Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=West%20Franklin%20Street,%20Chapel%20Hill,%20NC&sensor=false
## Warning: `panel.margin` is deprecated. Please use `panel.spacing` property
## instead

# Plot all chapel hill addresses in satellite view map to determine the distribution of voters

qmap('Flyleaf Books, Chapel Hill, NC', zoom = 13, maptype = 'satellite')+
    geom_polygon(data = plt,
                 aes(x = long, y = lat, group = group),
                 color = 'gray', fill = NA) +
    geom_point(data = chCoordinates, aes(x = latitude, y = longitude), color = 'red',size = 1.5, alpha = .3)
## Map from URL : http://maps.googleapis.com/maps/api/staticmap?center=Flyleaf+Books,+Chapel+Hill,+NC&zoom=13&size=640x640&scale=2&maptype=satellite&language=en-EN&sensor=false
## Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=Flyleaf%20Books,%20Chapel%20Hill,%20NC&sensor=false
## Warning: `panel.margin` is deprecated. Please use `panel.spacing` property
## instead
## Warning: Removed 2124 rows containing missing values (geom_point).

# Visualize problem of individual voters registering from out of county (mostly Durham, Chatham, and Wake counties) 

map2 <- ggplot() + 
    geom_polygon(data = plt,
                 aes(x = long, y = lat, group = group),
                 color = 'gray', fill = 'white') +
    geom_point(data = chCoordinates, aes(x = latitude, y = longitude), color = 'red',size = 2, alpha = .5)

plot(map2)
## Warning: Removed 203 rows containing missing values (geom_point).

### OLD CODE TO GEOCODE ADDRESSES 

# Create full length addresses

    fullAddress <- chCombined[!duplicated(chCombined[,"fullName"]),7:8]
    fullAddress$residentialStreet <- gsub('# ', '',fullAddress$residentialStreet)
    fullAddress <- transmute(fullAddress, address = paste(residentialStreet, residentialCity))
    
    coords <- data.frame(latitude = double(), longitude = double())

for (i in 1:nrow(fullAddress)){
   tryCatch({
    address <- (toString(fullAddress[i,1])) 
    Encoding(address)<- 'latin1'
    latLong <- street2coordinates(address)
    coords[i,] <- select(latLong, latitude, longitude)
   },
   
   error = function(e){cat("ERROR :", conditionMessage(e),"\n")})
  
}